package org.spring.aicloud;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import okhttp3.HttpUrl;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@SpringBootTest
class AicloudApplicationTests {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ObjectMapper objectMapper;

    @Test
    void xunfeiChat() throws JsonProcessingException {
        String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
        String authorization = "Bearer a9ae341df6970cea82f531cc6d2e256d:NWQ1Y2E5ZDdmYTE4ZDM0MTU0MTNmMGFk";
        String result = HttpRequest.post(url)
                .header("Authorization", authorization)
                .header("Content-Type", "application/json")
                .body("{\n" +
                        "    \"model\": \"4.0Ultra\",\n" +
                        "    \"messages\": [\n" +
                        "        {\n" +
                        "            \"role\": \"user\",\n" +
                        "            \"content\": \"你是谁\"\n" +
                        "        }\n" +
                        "    ],\n" +
                        "    \"stream\": false\n" +
                        "}").execute().body();
        HashMap<String, Object> map = objectMapper.readValue(result, HashMap.class);
        System.out.println(map.get("choices"));




    }

    @Test
    void xunfeiDraw() throws Exception {
        final String hostUrl = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti";
        String authUrl = getAuthUrl(hostUrl, "a9ae341df6970cea82f531cc6d2e256d", "NWQ1Y2E5ZDdmYTE4ZDM0MTU0MTNmMGFk");

        String json = "{\n" +
                "  \"header\": {\n" +
                "    \"app_id\": \"0de71fa4\"\n" +
                "    },\n" +
                "  \"parameter\": {\n" +
                "    \"chat\": {\n" +
                "      \"domain\": \"general\",\n" +
                "      \"width\": 512,\n" +
                "      \"height\": 512\n" +
                "      }\n" +
                "    },\n" +
                "  \"payload\": {\n" +
                "    \"message\": {\n" +
                "      \"text\": [\n" +
                "        {\n" +
                "          \"role\": \"user\",\n" +
                "          \"content\": \"帮我画一座山\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";
        String result = HttpRequest.post(authUrl).body(json).execute().body();
        HashMap<String, Object> map = objectMapper.readValue(result, HashMap.class);
        LinkedHashMap<String, Object> payload = (LinkedHashMap<String, Object>) map.get("payload");
        LinkedHashMap<String, Object> choices = (LinkedHashMap<String, Object>) payload.get("choices");
        ArrayList<LinkedHashMap> text = (ArrayList<LinkedHashMap>) choices.get("text");
        LinkedHashMap<String,Object> textFirst = text.get(0);
        String content = textFirst.get("content").toString();
        System.out.println(text);

//       InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(""));


    }

    // 鉴权方法
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

}
